﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace csharp_ftp
{
    class Program
    {
        private const int BUFFER_SIZE = 2048;

        static void Main(string[] args)
        {
            FtpWebRequest conn = retrieveConn(new Uri("ftp://localhost"), "khs", "khs1234");
            StreamReader streamReader = retrieveListDirectory(conn);
            Console.WriteLine(streamReader.ReadToEnd());

            streamReader.Close();

            conn = null;
        }

        static FtpWebRequest retrieveConn(Uri uri, String userid, String passwd)
        {
            FtpWebRequest conn = (FtpWebRequest)WebRequest.Create(uri);
            conn.Credentials = new NetworkCredential(userid, passwd);
            conn.Timeout = 1000;

            return conn;
        }

        static StreamReader retrieveListDirectory(FtpWebRequest conn)
        {
            conn.Method = WebRequestMethods.Ftp.ListDirectory;
            return new StreamReader(conn.GetResponse().GetResponseStream());
        }

        /*
         * FileStream(파일패스, FileMode.OpenOrCreate, FileAccess.Write);
         */
        static void downloadFile(FtpWebRequest conn, FileStream fs)
        {
            conn.Method = WebRequestMethods.Ftp.DownloadFile;
            StreamReader streamReader = new StreamReader(conn.GetResponse().GetResponseStream());

            StreamWriter streamWriter = new StreamWriter(fs);
            streamWriter.Write(streamReader.ReadToEnd());

            streamWriter.Flush();
            streamWriter.Close();
            streamReader.Close();
        }

        /**
         * FileStream(파일패스, FileMode.Open)
         */
        static void uploadFile(FtpWebRequest conn, FileStream fs)
        {
            conn.Method = WebRequestMethods.Ftp.UploadFile;
            Stream stream = conn.GetRequestStream();

            byte[] buffer = new byte[BUFFER_SIZE];
            int readCount = fs.Read(buffer, 0, BUFFER_SIZE);

            while (readCount > 0)
            {
                stream.Write(buffer, 0, readCount);
                readCount = fs.Read(buffer, 0, BUFFER_SIZE);
            }
            stream.Close();
        }
    }
}
